package top.yunmouren.areamusic.commannd;


import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.chat.hover.content.Text;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import top.yunmouren.areamusic.AreaMusic;
import top.yunmouren.areamusic.commannd.Adventure.MusicListMessage;
import top.yunmouren.areamusic.config.AreaDto;
import top.yunmouren.areamusic.config.MusicDto;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class MainExecutor implements CommandExecutor {
    private final AreaMusic plugin;

    public MainExecutor(AreaMusic plugin) {
        this.plugin = plugin;
    }

    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
        if (args.length == 0) {
            sender.sendMessage("§c[AreaMusic] 请使用 /am help 来参阅帮助");
            return true;
        } else if (!sender.hasPermission("area-music.admin")) {
            sender.sendMessage("§c[AreaMusic] 权限不足");
            return true;
        } else {
            String var5 = args[0];
            byte var6 = -1;
            switch(var5.hashCode()) {
                case -934641255:
                    if (var5.equals("reload")) {
                        var6 = 2;
                    }
                    break;
                case 3002509:
                    if (var5.equals("area")) {
                        var6 = 1;
                    }
                    break;
                case 3198785:
                    if (var5.equals("help")) {
                        var6 = 3;
                    }
                    break;
                case 104263205:
                    if (var5.equals("music")) {
                        var6 = 0;
                    }
            }

            String var7;
            byte var8;
            switch(var6) {
                case 0:
                    if (args.length < 2) {
                        sender.sendMessage("§c[AreaMusic] 请指定子指令");
                        return true;
                    } else {
                        var7 = args[1];
                        var8 = -1;
                        switch(var7.hashCode()) {
                            case 96417:
                                if (var7.equals("add")) {
                                    var8 = 0;
                                }
                                break;
                            case 99339:
                                if (var7.equals("del")) {
                                    var8 = 1;
                                }
                                break;
                            case 3322014:
                                if (var7.equals("list")) {
                                    var8 = 2;
                                }
                        }

                        switch(var8) {
                            case 0:
                                return this.handleAddMusic(sender, Arrays.copyOfRange(args, 2, args.length));
                            case 1:
                                return this.handleDelMusic(sender, Arrays.copyOfRange(args, 2, args.length));
                            case 2:
                                return this.handleListMusic(sender, Arrays.copyOfRange(args, 2, args.length));
                            default:
                                sender.sendMessage("§c[AreaMusic] 未匹配到 music 的子指令");
                                return true;
                        }
                    }
                case 1:
                    if (args.length < 2) {
                        sender.sendMessage("§c[AreaMusic] 请指定子指令");
                        return true;
                    } else {
                        var7 = args[1];
                        var8 = -1;
                        switch(var7.hashCode()) {
                            case 96417:
                                if (var7.equals("add")) {
                                    var8 = 0;
                                }
                                break;
                            case 99339:
                                if (var7.equals("del")) {
                                    var8 = 1;
                                }
                                break;
                            case 3322014:
                                if (var7.equals("list")) {
                                    var8 = 2;
                                }
                        }

                        switch(var8) {
                            case 0:
                                return this.handleAddArea(sender, Arrays.copyOfRange(args, 2, args.length));
                            case 1:
                                return this.handleDelArea(sender, Arrays.copyOfRange(args, 2, args.length));
                            case 2:
                                return this.handleListArea(sender, Arrays.copyOfRange(args, 2, args.length));
                            default:
                                sender.sendMessage("§c[AreaMusic] 未匹配到 area 的子指令");
                                return true;
                        }
                    }
                case 2:
                    return this.handleReload(sender, args);
                case 3:
                    return this.handleHelp(sender, args);
                default:
                    sender.sendMessage("§c[AreaMusic] 未匹配到指令");
                    return true;
            }
        }
    }

    public boolean handleAddMusic(CommandSender sender, String[] args) {
        if (args.length != 3) {
            sender.sendMessage("§c[AreaMusic] 要添加音乐，应该按照 musicId musicURL musicDuration(单位为秒) 的顺序输入数据");
            return true;
        } else {
            try {
                Long duration = Long.parseLong(args[2]);
                String musicId = args[0];
                String musicURL = args[1];
                String uuid = UUID.randomUUID().toString();
                if (!musicId.equals("") && !musicURL.equals("")) {
                    AtomicBoolean hasContainer = new AtomicBoolean(false);
                    this.plugin.getConfigManager().getMusics().forEach((key, value) -> {
                        if (value.getMusicId().equals(musicId)) {
                            hasContainer.set(true);
                        }

                    });
                    if (hasContainer.get()) {
                        sender.sendMessage("§c[AreaMusic] 已经存在 ID 为 " + musicId + " 的音乐");
                        return true;
                    } else {
                        this.plugin.getConfigManager().getMusics().put(uuid, MusicDto.builder().uuid(uuid).musicId(musicId).musicURL(musicURL).musicDuration(duration).build());
                        sender.sendMessage("§2[AreaMusic] 音乐 " + musicId + " 添加成功");
                        return true;
                    }
                } else {
                    sender.sendMessage("§c[AreaMusic] 参数错误");
                    return true;
                }
            } catch (NumberFormatException var8) {
                sender.sendMessage("§c[AreaMusic] 输入的 musicDuration 无效");
                return true;
            }
        }
    }

    public boolean handleDelMusic(CommandSender sender, String[] args) {
        if (args.length != 1) {
            sender.sendMessage("§c[AreaMusic] 要删除音乐，请输入音乐 ID");
            return true;
        } else if (args[0].equals("")) {
            sender.sendMessage("§c[AreaMusic] 要删除音乐，请输入音乐 ID");
            return true;
        } else {
            this.plugin.getConfigManager().getMusics().values().removeIf((item) -> {
                return item.getMusicId().equals(args[0]);
            });
            sender.sendMessage("§2[AreaMusic] 已删除音乐");
            return true;
        }
    }

    public boolean handleListMusic(CommandSender sender, String[] args) {
        int page = 0;
        if (args.length != 0) {
            try {
                page = Integer.parseInt(args[0]);
                if (page < 0) {
                    throw new NumberFormatException();
                }
            } catch (NumberFormatException var6) {
                sender.sendMessage("§c[AreaMusic] 页数错误");
                return true;
            }
        }

        sender.sendMessage(String.format("§a[AreaMusic] 音乐的列表如下（页码 %d）:", page));
        this.getPagedListMusic(page).forEach((musicDto) -> {
//            TextComponent textComponent = new TextComponent(musicDto.getMusicId());
//            textComponent.setUnderlined(true);
//            textComponent.setColor(ChatColor.WHITE);
//            textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("音乐插件内部 ID: " + musicDto.getUuid() + "\n音乐的客户端 ID: " + musicDto.getMusicURL() + "\n音乐的持续时间: " + musicDto.getMusicDuration() + " s")));
            sender.sendMessage(MusicListMessage.handleListMusic(musicDto));
        });
        TextComponent textComponentFront = new TextComponent("");
        TextComponent textComponent;
        if (page != 0) {
            textComponent = new TextComponent("<- 上一页 ");
            textComponent.setColor(ChatColor.GREEN);
            textComponent.setUnderlined(false);
            textComponent.setClickEvent(new ClickEvent(net.md_5.bungee.api.chat.ClickEvent.Action.RUN_COMMAND, "/am music list " + (page - 1)));
            textComponentFront.addExtra(textComponent);
        }

        textComponent = new TextComponent(" 下一页 ->");
        textComponent.setColor(ChatColor.GREEN);
        textComponent.setUnderlined(false);
        textComponent.setClickEvent(new ClickEvent(net.md_5.bungee.api.chat.ClickEvent.Action.RUN_COMMAND, "/am music list " + (page + 1)));
        textComponentFront.addExtra(textComponent);
        sender.spigot().sendMessage(textComponentFront);
        return true;
    }

    private List<MusicDto> getPagedListMusic(int page) {
        List<MusicDto> musicList = new ArrayList();
        int from = page * 9;
        int to = page * 9 + 8;
        int count = 0;

        for(Iterator<Map.Entry<String, MusicDto>> var6 = this.plugin.getConfigManager().getMusics().entrySet().iterator(); var6.hasNext(); ++count) {
            Map.Entry<String, MusicDto> item = var6.next();
            if (from <= count && count <= to) {
                musicList.add(item.getValue());
            }
        }

        return musicList;
    }

    public boolean handleAddArea(CommandSender sender, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage("§c[AreaMusic] 该指令只能够由玩家执行");
            return true;
        } else {
            Player player = (Player)sender;
            if (args.length != 1) {
                sender.sendMessage("§c[AreaMusic] 请指定子命令，可以是 enable，也可以是 finish");
                return true;
            } else if (args[0].equals("enable")) {
                this.plugin.getPlayerSelectionCache().setPlayerHistory(player.getUniqueId().toString(), new PlayerSelectionCache.CreateAreaDto());
                ItemStack itemStack = new ItemStack(Material.STICK);
                ItemMeta meta = itemStack.getItemMeta();

                assert meta != null;

                meta.setLore(Collections.singletonList("§aAreaMusic §3选择工具"));
                itemStack.setItemMeta(meta);
                player.getInventory().addItem(itemStack);
                sender.sendMessage("§a[AreaMusic] 已经激活交互式区域创建模式");
                return true;
            } else if (args[0].equals("finish")) {
                PlayerSelectionCache.CreateAreaDto createAreaDto = this.plugin.getPlayerSelectionCache().getPlayerHistory(player.getUniqueId().toString());
                if (createAreaDto == null) {
                    sender.sendMessage("§c[AreaMusic] 未检测到需要创建的区域");
                    return true;
                } else if (!this.checkCreateArgument(createAreaDto)) {
                    sender.sendMessage("§c[AreaMusic] 区域创建还未完成，请检查还未配置的项目");
                    sender.sendMessage("§c" + createAreaDto.toString());
                    return true;
                } else {
                    this.regularizationPoints(createAreaDto);
                    String uuid = UUID.randomUUID().toString();
                    Map<String, AreaDto> worldAreas = this.plugin.getConfigManager().getAreas().computeIfAbsent(createAreaDto.getWorld(), (k) -> {
                        return new HashMap();
                    });
                    Iterator<AreaDto> var7 = worldAreas.values().iterator();

                    AreaDto area;
                    do {
                        if (!var7.hasNext()) {
                            worldAreas.put(uuid, AreaDto.builder().world(createAreaDto.getWorld()).uuid(uuid).areaId(createAreaDto.getAreaId()).musicId(createAreaDto.getMusicId()).priority(createAreaDto.getPriority()).random(createAreaDto.getRandom()).loop(createAreaDto.getLoop()).enabled(createAreaDto.getEnabled()).overWrite(createAreaDto.getOverWrite()).volume(createAreaDto.getVolume()).pitch(createAreaDto.getPitch()).minPoint(createAreaDto.getMinPoint()).maxPoint(createAreaDto.getMaxPoint()).build());
                            sender.sendMessage("§a[AreaMusic] 区域创建成功");
                            this.plugin.getPlayerSelectionCache().setPlayerHistory(player.getUniqueId().toString(), null);
                            return true;
                        }

                        area = (AreaDto)var7.next();
                    } while(!area.getAreaId().equals(createAreaDto.getAreaId()));

                    sender.sendMessage("§c[AreaMusic] 已经存在该 ID 的区域，创建失败，请重试");
                    return true;
                }
            } else {
                sender.sendMessage("§c[AreaMusic] 未匹配到子指令，子指令可以是 enable，也可以是 finish");
                return true;
            }
        }
    }

    private boolean checkCreateArgument(PlayerSelectionCache.CreateAreaDto src) {
        if (src.getAreaId() != null && !src.getAreaId().equals("")) {
            if (src.getWorld() != null && !src.getWorld().equals("")) {
                if (src.getMusicId() != null && src.getMusicId().size() != 0) {
                    if (src.getPriority() == null) {
                        return false;
                    } else if (src.getRandom() == null) {
                        return false;
                    } else if (src.getLoop() == null) {
                        return false;
                    } else if (src.getEnabled() == null) {
                        return false;
                    } else if (src.getOverWrite() == null) {
                        return false;
                    } else if (src.getVolume() == null) {
                        return false;
                    } else if (src.getPitch() == null) {
                        return false;
                    } else if (src.getMinPoint() == null) {
                        return false;
                    } else {
                        return src.getMaxPoint() != null;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    private void regularizationPoints(PlayerSelectionCache.CreateAreaDto createAreaDto) {
        AreaDto.Point min = createAreaDto.getMinPoint();
        AreaDto.Point max = createAreaDto.getMaxPoint();
        double maxX = Math.max(min.getX(), max.getX());
        double maxY = Math.max(min.getY(), max.getY());
        double maxZ = Math.max(min.getZ(), max.getZ());
        double minX = Math.min(min.getX(), max.getX());
        double minY = Math.min(min.getY(), max.getY());
        double minZ = Math.min(min.getZ(), max.getZ());
        createAreaDto.setMinPoint(AreaDto.Point.builder().x(minX).y(minY).z(minZ).build());
        createAreaDto.setMaxPoint(AreaDto.Point.builder().x(maxX).y(maxY).z(maxZ).build());
    }

    public boolean handleDelArea(CommandSender sender, String[] args) {
        if (args.length != 1) {
            sender.sendMessage("§c[AreaMusic] 要删除区域，请输入区域 ID");
            return true;
        } else if (args[0].equals("")) {
            sender.sendMessage("§c[AreaMusic] 要删除区域，请输入正确的区域 ID");
            return true;
        } else {
            this.plugin.getConfigManager().getAreas().forEach((world, worldAreas) -> {
                worldAreas.values().removeIf((areaDto) -> {
                    return areaDto.getAreaId().equals(args[0]);
                });
            });
            sender.sendMessage("§2[AreaMusic] 已删除区域");
            return true;
        }
    }

    public boolean handleListArea(CommandSender sender, String[] args) {
        int page = 0;
        if (args.length != 0) {
            try {
                page = Integer.parseInt(args[0]);
                if (page < 0) {
                    throw new NumberFormatException();
                }
            } catch (NumberFormatException var6) {
                sender.sendMessage("§c[AreaMusic] 页数错误");
                return true;
            }
        }

        sender.sendMessage(String.format("§a[AreaMusic] 区域的列表如下（页码 %d）:", page));
        this.getPagedListArea(page).forEach((areaDto) -> {
            TextComponent textComponent = new TextComponent(areaDto.getAreaId());
            textComponent.setUnderlined(true);
            textComponent.setColor(ChatColor.WHITE);
            textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("区域插件内部 ID: " + areaDto.getUuid() + "\n区域 ID: " + areaDto.getAreaId() + "\n区域所在世界: " + areaDto.getWorld() + "\n区域所播放的音乐 ID:\n" + this.getMusicWithUUID(areaDto.getMusicId()) + "\n区域起始位点: " + areaDto.getMinPoint().getX() + " " + areaDto.getMinPoint().getY() + " " + areaDto.getMinPoint().getZ() + "\n区域结束位点: " + areaDto.getMaxPoint().getX() + " " + areaDto.getMaxPoint().getY() + " " + areaDto.getMaxPoint().getZ())));
            sender.spigot().sendMessage(textComponent);
        });
        TextComponent textComponentFront = new TextComponent("");
        TextComponent textComponent;
        if (page != 0) {
            textComponent = new TextComponent("<- 上一页 ");
            textComponent.setColor(ChatColor.GREEN);
            textComponent.setUnderlined(false);
            textComponent.setClickEvent(new ClickEvent(net.md_5.bungee.api.chat.ClickEvent.Action.RUN_COMMAND, "/am area list " + (page - 1)));
            textComponentFront.addExtra(textComponent);
        }

        textComponent = new TextComponent(" 下一页 ->");
        textComponent.setColor(ChatColor.GREEN);
        textComponent.setUnderlined(false);
        textComponent.setClickEvent(new ClickEvent(net.md_5.bungee.api.chat.ClickEvent.Action.RUN_COMMAND, "/am area list " + (page + 1)));
        textComponentFront.addExtra(textComponent);
        sender.spigot().sendMessage(textComponentFront);
        return true;
    }

    private String getMusicWithUUID(List<String> uuids) {
        StringBuilder finalStr = new StringBuilder();

        for (String uuid : uuids) {
            MusicDto musicDto = this.plugin.getConfigManager().getMusics().get(uuid);
            if (musicDto == null) {
                finalStr.append(uuid).append("\n");
            } else {
                finalStr.append(musicDto.getMusicId()).append("\n");
            }
        }

        return finalStr.toString();
    }

    private List<AreaDto> getPagedListArea(int page) {
        List<AreaDto> areaList = new ArrayList();
        int from = page * 9;
        int to = page * 9 + 8;
        int[] count = new int[]{0};
        this.plugin.getConfigManager().getAreas().forEach((world, worldAreas) -> {
            int var10002;
            for(Iterator<Map.Entry<String, AreaDto>> var6 = worldAreas.entrySet().iterator(); var6.hasNext(); var10002 = count[0]++) {
                Map.Entry<String, AreaDto> item = var6.next();
                if (from <= count[0] && count[0] <= to) {
                    areaList.add(item.getValue());
                }
            }

        });
        return areaList;
    }

    public boolean handleReload(CommandSender sender, String[] args) {
        sender.sendMessage("§2[AreaMusic] 正在尝试重载...");

        try {
            this.plugin.onReload();
            sender.sendMessage("§2[AreaMusic] 重载成功！");
        } catch (IOException var4) {
            sender.sendMessage("§c[AreaMusic] 重载失败:\n" + var4.getMessage() + "\n" + var4.getCause().getMessage());
        }

        return true;
    }

    public boolean handleHelp(CommandSender sender, String[] args) {
        TextComponent textComponent = new TextComponent("[AreaMusic] 请前往 ");
        textComponent.setColor(ChatColor.GREEN);
        TextComponent linkComponent = new TextComponent("这里");
        linkComponent.setColor(ChatColor.WHITE);
        linkComponent.setUnderlined(true);
        linkComponent.setClickEvent(new ClickEvent(net.md_5.bungee.api.chat.ClickEvent.Action.OPEN_URL, "https://gitee.com/niocho/AreaMusic/"));
        linkComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("点击打开 Area Music Gitee 文档")));
        TextComponent subComponent = new TextComponent(" 查看帮助");
        subComponent.setColor(ChatColor.GREEN);
        textComponent.addExtra(linkComponent);
        textComponent.addExtra(subComponent);
        sender.spigot().sendMessage(textComponent);
        return true;
    }
}
